# -*- coding: UTF-8 -*-
import fitz
from cv2 import *

import numpy as np
from PyCVParser import PyCVParser
from PyToolsParser import PyToolsParser

class PDFParser:
    '''主体类'''
    def __init__(self,filepath):
        try:
            self.doc = fitz.open(r'' + filepath)
        except Exception as e:
            print(e)

    def haveDataStructure(self):
        #文字识别需判断 扫描版还是电子版
        if(self.doc):
            if self.doc.getPageText(0):
                self.metadata =  self.doc.metadata
                return True
            else:
                return False
        else:
            return False


    def pdf2mat(self):
        matlist = []
        try:
            # 循环提取pdf页面
            for i in range(self.doc.pageCount):
                # 获取当前页内容
                page = self.doc[i]
                # 缩放及旋转
                zoom = 2.0
                rotate = 0
                trans = fitz.Matrix(zoom, zoom).preRotate(rotate)
                pm = page.getPixmap(matrix=trans, alpha=False)
                # 这里获取到数据流
                getpngdata = pm.getImageData(output="png")
                # 解码为 np.uint8
                image_array = np.frombuffer(getpngdata, dtype=np.uint8)
                img_cv = cv2.imdecode(image_array, cv2.IMREAD_ANYCOLOR)
                matlist.append(img_cv)
        except Exception as e:
            print(e)
        return matlist

    def extractImgandTab(self):
        cv_parser = PyCVParser()
        c = 0
        for srcimg in self.pdf2mat():
            gray = cv2.cvtColor(srcimg,cv2.COLOR_BGR2GRAY)#每一页灰度图像
            binsrc = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11,2) #每一页二值化图像

            mode = cv_parser.layout_mode(binsrc)
            cvimg = binsrc.copy()
            cvimg[0:binsrc.shape[0],0:binsrc.shape[1]] = 0

            for roi_pos in cv_parser.segment_rois(mode,binsrc.copy()):
                src_roi = binsrc.copy()
                src_roi[0:binsrc.shape[1], 0:binsrc.shape[0]] = 255
                src_roi[roi_pos[1]:roi_pos[1]+roi_pos[3] ,roi_pos[0]:roi_pos[0]+roi_pos[2]] = binsrc[roi_pos[1]:roi_pos[1]+roi_pos[3] ,roi_pos[0]:roi_pos[0]+roi_pos[2]]
                # cv2.namedWindow("Image")
                # cv2.imshow("Image", src_roi)
                # cv2.waitKey(0)
                # cv2.destroyAllWindows()
                img_pos = cv_parser.parse_image(src_roi,cvimg)
                # print(c,img_pos)
                if img_pos:
                    img = binsrc[img_pos[1]:img_pos[1] + img_pos[3], img_pos[0]:img_pos[0] + img_pos[2]]





    def getText(self):
        pass

if __name__ == '__main__':
    p = PDFParser("C:/Users/50385/Desktop/PDF/test/1.pdf")
    print(p.extractImgandTab())
    # page = p.doc.loadPage(1)
    # textpage = page.getTextPage()
    # print(p.doc[5].getImageBbox(p.doc[5].getImageList(True)[0]))
    # print(p.doc[5].rect)